<?php

namespace catchAdmin\basics\controller;

use catchAdmin\basics\model\OfficialLog as officialLogModel;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catcher\base\CatchRequest as Request;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;
use GuzzleHttp\Client;

class OfficialLog extends CatchAdmin
{
     protected $weixinApiUrl = 'http://118.196.21.30:5003';
//    protected $weixinApiUrl = 'http://localhost:5003';

    protected $client;

    public function __construct(officialLogModel $officialLogModel)
    {
        $this->officialLogModel = $officialLogModel;
        $this->client = new Client();
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->officialLogModel->getList($user['tenant_id']));
    }

    // 检查微信登录状态
    public function checkLoginStatus()
    {
        try {
            $response = $this->client->get($this->weixinApiUrl . '/api/weixin/login/status');
            $result = json_decode($response->getBody(), true);

            // //测试 在 /usr/src/teswin/weixinWen/log 写入文件
            // $logFile = '/usr/src/teswin/weixinWen/weixin_login_status'. date('Y-m-d') . '.log';
            // if(file_put_contents($logFile, date('Y-m-d H:i:s') . ' - ' . json_encode($result) . "\n", FILE_APPEND)){
            //     return CatchResponse::success($result['data'], $result['msg']);
            // }else{
            //     return CatchResponse::fail('写入日志失败');
            // }
            
            // 转换状态码
            if ($result['code'] === 0) {
                return CatchResponse::success($result['data'], $result['msg']);
            } else {
                return CatchResponse::fail($result['msg']);
            }
        } catch (\Exception $e) {
            return CatchResponse::fail('检查登录状态失败: ' . $e->getMessage());
        }
    }

    // 获取登录二维码
    public function getLoginQrcode()
    {
        try {
            $response = $this->client->post($this->weixinApiUrl . '/api/weixin/login/qrcode');
            $result = json_decode($response->getBody(), true);
            
            // 转换状态码
            if ($result['code'] === 0) {
                return CatchResponse::success($result['data'], $result['msg']);
            } else {
                return CatchResponse::fail($result['msg']);
            }
        } catch (\Exception $e) {
            return CatchResponse::fail('获取登录二维码失败: ' . $e->getMessage());
        }
    }

    // 检查扫码状态
    public function checkScanStatus()
    {
        try {
            $response = $this->client->post($this->weixinApiUrl . '/api/weixin/login/check');
            $result = json_decode($response->getBody(), true);
            
            // 转换状态码
            switch ($result['code']) {
                case 0: // 登录成功
                    // 如果登录成功且有 cookies 数据，解码并写入文件
                    if (isset($result['data']['cookies'])) {
                        $cookiesJson = base64_decode($result['data']['cookies']);
                        $cookieFile = '/usr/src/teswin/weixinWen/weixin_cookies.json';
                        if (file_put_contents($cookieFile, $cookiesJson)) {
                            return CatchResponse::success($result['data'], '登录成功');
                        } else {
                            return CatchResponse::fail('登录成功，保存失败');
                        }
                    }
                    return CatchResponse::success($result['data'], '登录成功');
                case 1: // 等待扫码或确认中
                    return CatchResponse::fail($result['msg'] ?? '等待扫码或确认中');
                case -1: // 登录失败
                    return CatchResponse::fail($result['msg'] ?? '登录失败');
                default:
                    return CatchResponse::fail('未知状态');
            }
        } catch (\Exception $e) {
            return CatchResponse::fail('检查扫码状态失败: ' . $e->getMessage());
        }
    }
}